package com.salon.client;

import java.util.ArrayList;
import java.util.List;
import com.extjs.gxt.ui.client.Style;
import com.extjs.gxt.ui.client.event.ButtonEvent;
import com.extjs.gxt.ui.client.event.Events;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.event.SelectionListener;
import com.extjs.gxt.ui.client.event.TabPanelEvent;
import com.extjs.gxt.ui.client.util.Margins;
import com.extjs.gxt.ui.client.widget.ContentPanel;
import com.extjs.gxt.ui.client.widget.Html;
import com.extjs.gxt.ui.client.widget.Info;
import com.extjs.gxt.ui.client.widget.LayoutContainer;
import com.extjs.gxt.ui.client.widget.MessageBox;
import com.extjs.gxt.ui.client.widget.TabItem;
import com.extjs.gxt.ui.client.widget.TabPanel;
import com.extjs.gxt.ui.client.widget.Text;
import com.extjs.gxt.ui.client.widget.Viewport;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.form.FormPanel;
import com.extjs.gxt.ui.client.widget.form.Radio;
import com.extjs.gxt.ui.client.widget.form.RadioGroup;
import com.extjs.gxt.ui.client.widget.form.TextField;
import com.extjs.gxt.ui.client.widget.form.FormPanel.LabelAlign;
import com.extjs.gxt.ui.client.widget.layout.BorderLayout;
import com.extjs.gxt.ui.client.widget.layout.BorderLayoutData;
import com.extjs.gxt.ui.client.widget.layout.FitLayout;
import com.extjs.gxt.ui.client.widget.layout.FlowData;
import com.extjs.gxt.ui.client.widget.layout.FlowLayout;
import com.extjs.gxt.ui.client.widget.layout.FormData;
import com.extjs.gxt.ui.client.widget.layout.RowData;
import com.extjs.gxt.ui.client.widget.layout.RowLayout;
import com.extjs.gxt.ui.client.widget.layout.TableData;
import com.extjs.gxt.ui.client.widget.layout.TableRowLayout;
import com.extjs.gxt.ui.client.widget.layout.FormLayout;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONParser;
import com.google.gwt.json.client.JSONValue;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.rpc.StatusCodeException;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.PushButton;
import com.google.gwt.user.client.ui.Widget;
import com.salon.client.tabItems.ClientTabItemPanel;
import com.salon.client.tabItems.CurrentMaterialTabItemPanel;
import com.salon.client.tabItems.IncomeTabItemPanel;
import com.salon.client.tabItems.MasterTabItemPanel;
import com.salon.client.tabItems.MaterialTabItemPanel;
import com.salon.client.tabItems.OutcomeMaterialTabItemPanel;
import com.salon.client.tabItems.PriceTabItemPanel;
import com.salon.client.tabItems.ProcedureTabItemPanel;
import com.salon.client.tabItems.SchedulerTabItemPanel;
import com.salon.client.tabItems.WorkDateTabItemPanel;

/**
 * MainView is the Main Viewport that contains the header, tab and detail areas.
 * 
 * <p>
 * Copyright (C) 2008 by BRIT Systems, Inc.
 * <p>
 * This software and the associated documentation are the property of BRIT
 * Systems. You may not copy, modify, merge or transfer copies of this software
 * without written permission from BRIT Systems. You may not reverse assemble or
 * reverse compile this software. You may not sublicense, rent, lease or assign
 * this software without written permission from BRIT Systems. Unauthorized use
 * of the software and associated documentation is contrary to the property
 * rights of BRIT Systems and is a violation of state and federal law. This
 * material must be returned to BRIT Systems upon demand. This copyright notice
 * must not be removed, altered, or obscured.
 * <p>
 * 
 * $Id: MainView.java,v 1.43 2009/09/21 16:30:59 barton Exp $
 * <p>
 * 
 * @author Robbie Barton
 * @version $Revision: 1.43 $
 * @since Oct 21, 2008
 * 
 */
public class MainView extends Viewport {

	private static MainView mainView;
	private Radio radio = new Radio();
	private Radio radio2 = new Radio();
	private Radio radio3 = new Radio();
	
	private TabPanel tabs = new TabPanel();
	private TabItem applicantTab = new TabItem("Клиенты");
	private TabItem employerTab = new TabItem("Работники");
	private TabItem workDayTab = new TabItem("Рабочие дни");
	private TabItem vacancyTab = new TabItem("Расходные материалы");
	private TabItem incomeTab = new TabItem("Приход");
	private TabItem priceTab = new TabItem("Услуги");
	private TabItem procedureTab = new TabItem("Процедуры");
	private TabItem schedulerTab = new TabItem("Расписание процедур");
	private TabItem currentMaterialTab = new TabItem("Текущее состояние материалов");
	private TabItem outcomeTab = new TabItem("Расход");
	private  TextField<String> quicksearch = new TextField<String>();
	
	public enum State { LOGGINGIN, REGISTERING, LOGGEDIN };
	private State state;
	
	ContentPanel bottomPanel = new ContentPanel();
	//private AdvancedSearchDialog searchDialog;
	
	private boolean firstTry = true;
	
	public enum Layout { TABS, SIMPLE };
	private Layout layout = Layout.TABS;
		
	public MainView() {
		mainView = this;
		setBorders(false);
		setStyleName("brit-main-view");
	}
		
	protected void onLoad() {
		initTabs();
	}
	
	
	private void initTabs() {		
		layout = Layout.TABS;
		state = State.LOGGEDIN;
		removeAll();
		
		History.newItem("Welcome to Salon Manager", false);
		
		BorderLayout layout = new BorderLayout();
		setLayout(layout);
		setScrollMode(Style.Scroll.NONE);
		
		Window.setTitle("Welcome to Salon Manager");

		TabPanel tabs = new TabPanel();
		

		applicantTab.setLayout(new FitLayout());
		applicantTab.add(new ClientTabItemPanel("Клиенты"));
		applicantTab.addListener(Events.Select, new TabListener());
		tabs.add(applicantTab);
		
		employerTab.setLayout(new FitLayout());
		employerTab.add(new MasterTabItemPanel("Работники"));
		employerTab.addListener(Events.Select, new TabListener());
		tabs.add(employerTab);
		
		workDayTab.setLayout(new FitLayout());
		workDayTab.add(new WorkDateTabItemPanel());
		workDayTab.addListener(Events.Select, new TabListener());
		tabs.add(workDayTab);
		
		vacancyTab.setLayout(new FitLayout());
		vacancyTab.add(new MaterialTabItemPanel("Расходные материалы"));
		tabs.add(vacancyTab);
		
		currentMaterialTab.setLayout(new FitLayout());
		currentMaterialTab.add(new CurrentMaterialTabItemPanel("Текущее состояние материалов"));
		tabs.add(currentMaterialTab);
		
		
		incomeTab.setLayout(new FitLayout());
		incomeTab.add(new IncomeTabItemPanel());
		tabs.add(incomeTab);
		
		outcomeTab.setLayout(new FitLayout());
		outcomeTab.add(new OutcomeMaterialTabItemPanel("Расход"));
		tabs.add(outcomeTab);
		
		priceTab.setLayout(new FitLayout());
		priceTab.add(new PriceTabItemPanel());
		tabs.add(priceTab);
		
		procedureTab.setLayout(new FitLayout());
		procedureTab.add(new ProcedureTabItemPanel("Процедуры"));
		tabs.add(procedureTab);
		
		schedulerTab.setLayout(new FitLayout());
		schedulerTab.add(new SchedulerTabItemPanel());
		tabs.add(schedulerTab);
		
		BorderLayoutData bcd = new BorderLayoutData(Style.LayoutRegion.CENTER);
		bcd.setMargins(new Margins(0, 0, 0, 0));

		// The top panel contains the logo and other items
		ContentPanel topPanel = new ContentPanel();
		BorderLayout topLayout = new BorderLayout();
		topPanel.setLayout(topLayout);
		topPanel.setBodyStyleName("brit-top-panel");
		topPanel.setHeaderVisible(false);
		topPanel.setBorders(false);
		topPanel.setBodyBorder(false);
		BorderLayoutData btd = new BorderLayoutData(Style.LayoutRegion.NORTH);
		btd.setSize(46);
		btd.setMinSize(46);
		btd.setMaxSize(46);
		btd.setMargins(new Margins(0, 0, -2, 0));
		
		LayoutContainer topMiddle = new LayoutContainer(new RowLayout(Style.Orientation.HORIZONTAL));
		topMiddle.setStyleName("brit-transparent");
		topMiddle.setBorders(false);
		BorderLayoutData topMiddleData = new BorderLayoutData(Style.LayoutRegion.CENTER);
		topMiddleData.setMargins(new Margins(2, 1, 0, 1));
		//topPanel.add(topMiddle, topMiddleData);

		LayoutContainer topRight = new LayoutContainer(new RowLayout(Style.Orientation.HORIZONTAL));
		topRight.setStyleName("brit-transparent");
		topRight.setBorders(false);
		BorderLayoutData topRightData = new BorderLayoutData(Style.LayoutRegion.EAST);
		topRightData.setSize(190);
		topRightData.setMinSize(190);
		topRightData.setMaxSize(190);
		topRightData.setMargins(new Margins(2, 1, 0, 1));
		topPanel.add(topRight, topRightData);
		
		Image logo = new Image("salon/icons/brit/salon_logo.png");
		BorderLayoutData topLeftData = new BorderLayoutData(Style.LayoutRegion.WEST);
		topLeftData.setSize(312);
		topLeftData.setMinSize(312);
		topLeftData.setMaxSize(312);
		topLeftData.setMargins(new Margins(2, 1, 0, 1));
		topPanel.add(logo, topLeftData);
		
		/*final Button searchBtn = new Button("Быстрый поиск");
		searchBtn.addSelectionListener(new SelectionListener<ButtonEvent>() {

			@Override
			public void componentSelected(ButtonEvent ce) {
				quickSearch();
				
			}
			
		});*/
// TODO:		searchBtn.setStyleName("brit-study-quicksearch");
		final RadioGroup searchBy = new RadioGroup("searchby");
		
		// creating the form for quick search
		FormPanel form = new FormPanel();
		form.setBorders(false);
		form.setBodyBorder(false);
		form.setHeaderVisible(false);
		form.setAutoWidth(true);
		form.setPadding(0);
		form.setBodyStyleName("brit-top-panel");
		TableRowLayout formLayout = new TableRowLayout();
		formLayout.setCellSpacing(4);
		form.setLayout(formLayout);
		
		// quick search options
		quicksearch.setAllowBlank(true);
		quicksearch.setWidth(300);
		quicksearch.setHeight(25);
		TableData td1 = new TableData();
		td1.setHorizontalAlign(Style.HorizontalAlignment.RIGHT);
		td1.setPadding(0);
		td1.setWidth("300px");
		td1.setHeight("25px");
		form.add(quicksearch, td1);
		
		// searchBtn config
		/*searchBtn.setWidth("100px");
		form.add(searchBtn);*/
		
		// searchby configuration
		radio.setName("searchradio");
		radio.setBoxLabel("Соискатели");
		radio.setValue(true);
		radio.setData("value", "name"); // "name" refers to patient name on the server
		radio2.setName("searchradio");
		radio2.setBoxLabel("Работодатели");
		radio2.setValue(false);
		radio2.setData("value", "id"); // "id" refers to patient id on the server
		radio3.setName("searchradio");
		radio3.setBoxLabel("Вакансии");
		radio3.setValue(false);
		radio3.setData("value", "acc"); // "acc" refers to accession number on the server
		searchBy.setFieldLabel("Quick Search By");
		searchBy.add(radio);
		searchBy.add(radio2);
		searchBy.add(radio3);
		form.add(searchBy);
		
		topMiddle.add(form, new RowData(600, 30, new Margins(0, 1 ,0, 1)));

		PushButton searchButton = new PushButton(new Image("salon/icons/glyphlab/search.png"),
				new ClickHandler() {
					public void onClick(ClickEvent e) {
						/*if (searchDialog == null)
							searchDialog = new AdvancedSearchDialog(slp);
						searchDialog.show();*/
					}});
		searchButton.setTitle("Open Advanced Search");
		searchButton.setStylePrimaryName("brit-top-options");
		searchButton.setSize("35px", "35px");
		topRight.add(searchButton, new RowData(47, 35, new Margins(2, 1, 0, 10)));
		
		PushButton optionsButton = new PushButton(new Image("salon/icons/glyphlab/options.png"),
				new ClickHandler() {
					public void onClick(ClickEvent e) {
						//new SettingsDialog();
						//WizardDialog.showWizard(null);
					}});
		optionsButton.setTitle("Открыть настройки");
		optionsButton.setStylePrimaryName("brit-top-options");
		optionsButton.setSize("35px", "35px");
		topRight.add(optionsButton, new RowData(47, 35, new Margins(2, 1, 0, 10)));
		
		PushButton logoutButton = new PushButton(new Image("salon/icons/glyphlab/logout.png"),
				new ClickHandler() {
					public void onClick(ClickEvent e) {
						/*searchDialog = null;
						ClientFoundation.logout();
						initLogin();*/
					}});
		logoutButton.setTitle("Logout");
		logoutButton.setStylePrimaryName("brit-top-logout");
		logoutButton.setSize("35px", "35px");
		topRight.add(logoutButton, new RowData(47, 35, new Margins(2, 1, 0, 10)));
		
		// The Detail Panel is at the botton, showing mostly salon/icons

		bottomPanel.setBorders(false);
		bottomPanel.setHeading("Детальная информация");
		//bottomPanel.setHeaderVisible(false);
		//bottomPanel.setCollapsible(true);
		bottomPanel.setBodyBorder(false);
		bottomPanel.setLayout(new FitLayout());
		//bottomPanel.add(ClientFoundation.getDetailPanel());
		bottomPanel.add(new Html("<font aling='center'>Подробная информация о сущности</font>"));
		BorderLayoutData bbd = new BorderLayoutData(Style.LayoutRegion.SOUTH);
		bbd.setFloatable(true);
		bbd.setCollapsible(true);
		bbd.setSplit(true);
		bbd.setSize(200);
		bbd.setMinSize(0);
		bbd.setMaxSize(350);
		//bbd.setMargins(new Margins(2, 16, 5, 15));
		bbd.setMargins(new Margins(1, 1, 0, 1));
		
		
		/*
		 * Here I create the SelectionListener because this is the only
		 * place that I can have the button listen for a click and react by
		 * calling the special quickSearch method in the StudyListPanel.
		 */
		// TODO - This doesn't feel very natural.
		/*final SelectionListener<ButtonEvent> quickListener = new SelectionListener<ButtonEvent>() {
			private TextField<String> quick = quicksearch;
			@Override
			public void componentSelected(ButtonEvent ce) {
				if ((quick.getValue() == null) || (quick.getValue().length() == 0)) {
					quick.forceInvalid("Required field");
					quick.focus();
					return;
				}
				quick.clearInvalid();
				List<TabItem> items = ClientFoundation.getTabPanel().getItems();
				for (TabItem item : items) {
					Widget widget = item.getItem(0);
					if (widget == null)
						continue;
					
					if (widget != slp)
						continue;

					ClientFoundation.getTabPanel().setSelection(item);
				}
				String str = (String) searchBy.getValue().getData("value");
				Info.display("Quick Search", "Quick Search for "+str+": "+quick.getValue());
				LinkedList<WhereBean> where = new LinkedList<WhereBean>();
				where.add(new WhereBean(str, WhereBean.Operator.LIKE, "%"+quick.getValue().toUpperCase()+"%"));
				if (slp != null)
					slp.search(where, true);
			}
		};
		searchBtn.addListener(Events.Select, quickListener);
		// Add code to cause Enter in Password to trigger the Login button.
		quicksearch.addKeyListener(new KeyListener() {
			public void componentKeyUp(ComponentEvent event) {
				if (event.getKeyCode() == 13) {
					// Just call the callback method, it doesn't use the parameter.
					quickListener.componentSelected(null);
				}
			}
		});*/
		//add(bottomPanel, bbd);
		add(topPanel, btd);
		add(tabs, bcd);
		layout();
		
		// Start getting updates.
		//Updater.startUpdater();
		
		History.fireCurrentHistoryState();

	}
	
	
	class TabListener implements Listener<TabPanelEvent>{
		public void handleEvent(TabPanelEvent be) {
			TabItem tab = be.getItem();
			if (tab == null) {
				return;
			}
			Widget widget = tab.getItem(0);
			
			/*if (widget != null && widget instanceof ApplicantList) {
				bottomPanel.removeAll();
				//bottomPanel.removeAllListeners();
				bottomPanel.add(((ApplicantList)widget).getForm());
				bottomPanel.layout();
			}
			else if (widget != null && widget instanceof EmployerList) {
				bottomPanel.removeAll();
				//bottomPanel.removeAllListeners();
				bottomPanel.add(((EmployerList)widget).getForm());
				bottomPanel.layout();
			}*/
		}
	};
	
	/**
	 * Get the main view
	 * @return the mainView
	 */
	public static MainView getMainView() {
		return mainView;
	}
	
	public State getLoginState() {
		return state;
	}
}